﻿using System.Text;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;

using VSTalk.Engine.Core.ExtElement;

using agsXMPP.protocol.client;

namespace VSTalk.Engine.ViewModel.Messenger.MessageBuilder
{
    public class XamlMessageBuilder : IMessageBuilder
    {
        public Message Create(FlowDocument document)
        {
            var xdoc = new XmlDocument();
            xdoc.LoadXml(XamlWriter.Save(document));
            
            var newAttr = xdoc.CreateAttribute("xml:space");
            newAttr.Value = "preserve";
            
            xdoc.DocumentElement.Attributes.Append(newAttr);
            var sb = new StringBuilder(xdoc.OuterXml);
            //see: http://stackoverflow.com/questions/2624068/wpf-richtextbox-xamlwriter-behaviour
            var xamlPart = sb.Replace("{}{", "{").ToString();

            var txtPart = new TextRange(document.ContentStart, document.ContentEnd)
                    .Text
                    .TrimEnd();
            var xaml = new XamlBody();
            xaml.Content = xamlPart;
            var msg = new Message
            {
                    Body = txtPart,
            };
            msg.AddChild(xaml);
            return msg;
        }
    }
}